package com.ygqh.baby.service.impl;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.mapper.KidsOrderLogisticsMapper;
import com.ygqh.baby.model.wdt.qyb.WdtSyncLogistics;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.KidsOrderLogisticsService;
import com.ygqh.baby.service.YgOrderDetailService;
import com.ygqh.baby.service.YgReturnOrderDetailService;
import com.ygqh.baby.service.YgReturnOrderService;
import com.ygqh.baby.service.wdtqyb.builder.WdtOrderBuiler;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class KidsOrderLogisticsServiceImpl implements KidsOrderLogisticsService{
	
	@Autowired
	private KidsOrderLogisticsMapper kidsOrderLogisticsMapper;
	@Autowired
	private YgOrderDetailService ygOrderDetailService;
	@Autowired
	private YgReturnOrderDetailService ygReturnOrderDetailService;
	@Autowired
	private YgReturnOrderService ygReturnOrderService;
	
	@Override
	public List<KidsOrderLogistics> find() {
		KidsOrderLogisticsExample example = new KidsOrderLogisticsExample();
		example.createCriteria();
		return kidsOrderLogisticsMapper.selectByExample(example);
	}

	@Override
	public int findCount() {
		KidsOrderLogisticsExample example = new KidsOrderLogisticsExample();
		example.createCriteria();
		return kidsOrderLogisticsMapper.countByExample(example);
	}

	@Override
	public KidsOrderLogistics findById(Long id) {
		return kidsOrderLogisticsMapper.selectByPrimaryKey(id);
	}


	

	@Override
	public int save(KidsOrderLogistics kidsOrderLogistics) {
		return kidsOrderLogisticsMapper.insertSelective(kidsOrderLogistics);
	}

	@Override
	public int update(KidsOrderLogistics kidsOrderLogistics) {
		return kidsOrderLogisticsMapper.updateByPrimaryKeySelective(kidsOrderLogistics);
	}

	@Override
	public ResultSet<KidsOrderLogistics> search(QueryInfo queryInfo,String orderId,Boolean isSync) {
		int count = kidsOrderLogisticsMapper.countSuper(orderId,isSync);
		List<KidsOrderLogistics>  list ;
		if(count > 0){
			   list =  kidsOrderLogisticsMapper.selectSuper(queryInfo, orderId,isSync);
		}else{
			list = Collections.emptyList();
		}
		return new ResultSet<>(count, list);
	}
	

	@Override
	public int saveOrUpdate(KidsOrderLogistics kidsOrderLogistics) {
		int r;
		if(kidsOrderLogistics.getId() != null) {
			r = this.update(kidsOrderLogistics);
		}else {
			r = this.save(kidsOrderLogistics);
		}
		return r;
	}

	@Override
	public void loadKidsLogistics(List<WdtSyncLogistics> trades) {
		if(trades.isEmpty()){
			return;
		}

		List<WdtSyncLogistics> kidsOrderLogisticsList = new ArrayList<>();

		List<WdtSyncLogistics> kidsOrderList = trades.stream().filter(wdtSyncLogistics -> {
			String orderCode = WdtOrderBuiler.getOrderIdFromTid(wdtSyncLogistics.getTid());
			wdtSyncLogistics.setTid(orderCode);
			return orderCode.startsWith(Constant.KIDS_ORDER_PREFIX) || orderCode.startsWith(Constant.OFF_ORDER_PREFIX);
		}).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(kidsOrderList)) {
			loadKidsOrderLogistics(kidsOrderList);
			kidsOrderLogisticsList.addAll(kidsOrderList);
		}

		List<WdtSyncLogistics> kidsChangeOrderList = trades.stream().filter(wdtSyncLogistics -> {
			String returnCode = WdtOrderBuiler.getOrderIdFromTid(wdtSyncLogistics.getTid());
			wdtSyncLogistics.setTid(returnCode);
			return returnCode.startsWith(Constant.KIDS_CHANGE_ORDER_PREFIX) ||
					returnCode.startsWith(Constant.OFF_CHANGE_ORDER_PREFIX);
		}).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(kidsChangeOrderList)) {
			loadKidsChangeOrderLogistics(kidsChangeOrderList);
			kidsOrderLogisticsList.addAll(kidsChangeOrderList);
		}

		if (CollectionUtils.isNotEmpty(kidsOrderLogisticsList)) {
			this.addBatch(kidsOrderLogisticsList);
		}
	}

	private void loadKidsChangeOrderLogistics(List<WdtSyncLogistics> kidsChangeOrderList) {
		if(CollectionUtils.isEmpty(kidsChangeOrderList)){
			return;
		}
		List<String> returnCodeList = kidsChangeOrderList.stream().map(WdtSyncLogistics::getTid).collect(Collectors.toList());

		List<YgReturnOrderDetail> returnOrderDetailList = ygReturnOrderDetailService.findByReturnCodeList(returnCodeList);
		Map<String, List<YgReturnOrderDetail>> collect = returnOrderDetailList.stream().collect(Collectors.groupingBy(YgReturnOrderDetail::getReturnCode));

		List<YgReturnOrder> updateOrderList = new ArrayList<>();
		List<YgReturnOrderDetail> updateDetailList = new ArrayList<>();
		List<Long> updateOrderDetailIdList = new ArrayList<>();
		Date now = new Date();
		kidsChangeOrderList.forEach(l -> {
			YgReturnOrder returnOrder = ygReturnOrderService.findByReturnCode(l.getTid());
			List<YgOrderDetail> orderDetailList = ygOrderDetailService.findByOrderId(returnOrder.getOrderId());
			List<YgReturnOrderDetail> list = collect.get(l.getTid());
			if(l.getIsPartSync() == 1){
				// 部分发货
				List<String> oidList = Arrays.asList(l.getOids().split(","));
				list = list.stream().filter(returnOrderDetail -> {
					String key = returnOrderDetail.getReturnCode() + "-" + returnOrderDetail.getId();
					return oidList.contains(key);
				}).collect(Collectors.toList());
			} else {
				YgReturnOrder update = new YgReturnOrder();
				update.setReturnCode(l.getTid());
				update.setReturnStatus(ReturnStatus.WaitingSign);
				update.setSendTime(now);
				update.setUpdateTime(now);
				update.setUpdateBy("loadOrderLogistics");
				updateOrderList.add(update);
			}

			list.forEach(rod -> {
				YgReturnOrderDetail detail = new YgReturnOrderDetail();
				detail.setId(rod.getId());
				detail.setSendMark(l.getLogisticsNo());
				detail.setDetailStatus(OrderDetailStatus.WaitingSign);
				updateDetailList.add(detail);

				if (CollectionUtils.isNotEmpty(orderDetailList)) {
					orderDetailList.forEach(od -> {
						if (od.getId().equals(rod.getOdId())) {
							updateOrderDetailIdList.add(od.getId());
						}
					});
				}
			});

			String[] array = list.stream().map(YgReturnOrderDetail::getRemark).toArray(String[]::new);
			l.setKidsOids(StringUtil.join(array, ",".charAt(0)));
			l.setCreateTime(now);
			l.setUpdateTime(now);
		});
		ygReturnOrderService.updateReturnStatusByReturnCode(updateOrderList);
		ygReturnOrderDetailService.updateSendBatch(updateDetailList);

		ygOrderDetailService.updateRefundStatusById(updateOrderDetailIdList, RefundStatus.RefundSuccess);
	}

	private void loadKidsOrderLogistics(List<WdtSyncLogistics> kidsOrderList) {
		if(kidsOrderList.isEmpty()){
			return;
		}
		String[] orderIdStr = kidsOrderList.stream().map(WdtSyncLogistics::getTid).toArray(String[]::new);
		Long[] orderIds = (Long[]) ConvertUtils.convert(orderIdStr,Long.class);
		List<YgOrderDetail> detailList = ygOrderDetailService.findByOrderIds(orderIds);
		Map<Long, List<YgOrderDetail>> collect = detailList.stream().collect(Collectors.groupingBy(YgOrderDetail::getOrderId));
		kidsOrderList.forEach(l->{
			String tid = l.getTid();
			List<YgOrderDetail> list = collect.get(Long.parseLong(tid));
			Stream<YgOrderDetail> stream = list.stream();
			if(l.getIsPartSync()==1){
				List<String> split = Arrays.asList(l.getOids().split(","));
				stream =stream.filter(od -> {
					String key = od.getOrderId() + "-" + od.getId();
					return split.contains(key);
				});

			}
			String[] array = stream.map(YgOrderDetail::getRemark).toArray(String[]::new);
			l.setKidsOids(StringUtil.join(array, ",".charAt(0)));
			l.setCreateTime(new Date());
			l.setUpdateTime(new Date());
		});
	}

	private int addBatch(List<WdtSyncLogistics> kidsList) {
		if(CollectionUtils.isEmpty(kidsList)){
			return 0;
		}

		return kidsOrderLogisticsMapper.addBatch(kidsList);
	}

	@Override
	public int updateSyncSuccessByTid(List<String> orderList) {
		if(CollectionUtils.isEmpty(orderList)){
			return 0;
		}
		return kidsOrderLogisticsMapper.updateSyncSuccessByTid(orderList);
	}

	@Override
	public int addBatchByYgLogistics(List<YgLogistics> ygLogistics) {
		if(CollectionUtils.isEmpty(ygLogistics)){
			return 0;
		}
		Date date = new Date();
		List<WdtSyncLogistics> list =new ArrayList<>(ygLogistics.size());
		ygLogistics.stream().filter(l->
				l.getOrderId().startsWith(Constant.KIDS_ORDER_PREFIX) ||
						l.getOrderId().startsWith(Constant.KIDS_CHANGE_ORDER_PREFIX) ||
						l.getOrderId().startsWith(Constant.OFF_ORDER_PREFIX) ||
						l.getOrderId().startsWith(Constant.OFF_CHANGE_ORDER_PREFIX))
				.forEach(l->{
			WdtSyncLogistics wdt = new WdtSyncLogistics();
			wdt.setShopNo("第三方");
			wdt.setTid(l.getOrderId());
			wdt.setLogisticsNo(l.getExpressCode());
			wdt.setLogisticsType(5);
			wdt.setDeliveryTerm("1");
			wdt.setConsignTime(l.getSendTime());
			wdt.setIsPartSync(0);
			wdt.setLogisticsName(l.getExpressCompany());
			wdt.setCreateTime(date);
			wdt.setUpdateTime(date);
			list.add(wdt);
		});
		return this.addBatch(list);
	}

	@Override
	public int updateSyncSuccessById(List<Long> idList) {
		if(CollectionUtils.isEmpty(idList)){
			return 0;
		}
		return kidsOrderLogisticsMapper.updateSyncSuccessById(idList);
	}


	

}

